import { entryInfoUrl, entrySubmitUrl, entrySaveUrl, userInfoUrl } from '../../../../api/individual'
import { conpanyDetailUrl } from '../../../../api/index'
import { post, get, getMessageAuth } from '../../../../utils/index'

Page({
  data: {
    page: '',
    form: {
      photoId: '',
      works: [],
      studys: [],
      family: [],
      medicalReportFileList: []
    },
    userStatus: {}
  },
  loadUserStatus () { // 获取用户状态
    const userStatus = wx.getStorageSync('userStatus')
    this.setData({ userStatus })
  },
  async loadData () { // 获取人员信息
    const { page } = this.data
    const url = page === 'entry' ? entryInfoUrl : userInfoUrl
    const { data } = await post(url)
    data.companyName = data.companyVO && data.companyVO.name
    data.socialSecurityFundOnly = data.companyVO && data.companyVO.socialSecurityFundOnly
    this.setData({ form: data })
    if (page === 'entry' && !data.confirmId) {
      this.bindConfirmId()
    }
  },
  async bindConfirmId () { // 绑定批次id和公司id
    const companyId = wx.getStorageSync('companyId')
    const confirmId = wx.getStorageSync('confirmId')
    if (!confirmId || !companyId) {
      wx.clearStorageSync()
      wx.showToast({
        title: '您不是本公司的派遣员工，若您需要入职，请联系人事',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.reLaunch({ url: '/pages/login/login' })
          }, 1000)
        }
      })
      return
    }
    const { form } = this.data
    form.confirmId = confirmId
    form.companyId = companyId
    const { data } = await get(conpanyDetailUrl, { id: form.companyId })
    this.setData({
      form,
      'form.companyName': data.name,
      'form.companyVO': data
    })
    await post(entrySaveUrl, form)
    wx.removeStorageSync('companyId')
    wx.removeStorageSync('confirmId')
  },
  async submit () { // 提交信息
    const { form, form: { studys, family, companyId, confirmId } } = this.data
    if (!form.householdLocationCode) {
      wx.showToast({ title: '请先完善员工信息，再提交审核', icon: 'none' })
      return
    }
    if (!studys.length) {
      wx.showToast({ title: '请填写至少一项最高学历，再提交审核', icon: 'none' })
      return
    }
    if (!family.length) {
      wx.showToast({ title: '请填写至少一名家庭成员，再提交审核', icon: 'none' })
      return
    }
    if (form.health !== '0') {
      wx.showToast({ title: '请在健康状况勾选无重大伤病，再提交审核', icon: 'none' })
      return
    }
    if (!companyId || !confirmId) {
      wx.showToast({ title: '您不是本公司的派遣员工，若您需要入职，请联系人事', icon: 'none' })
      return
    }
    await post(entrySubmitUrl, form)
    wx.navigateTo({ url: '/pages/individual/entry/status/status' })
    getMessageAuth()
  },
  onShow () {
    this.loadData()
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    this.setData({ page })
    this.loadUserStatus()
  }
})